# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '13592836171': {  # 测试
        'API_KEY': 'aefc0c9b55a9b56d80f3753a4640d832',
        'gateway': 'http://39.108.55.15/payapi.php/Home/Transfer/pay',
        'query_gateway': 'http://39.108.55.15/payapi.php/Home/Transfer/pay',
    },
    '13824370900': {
        'API_KEY': '9647c1cacabba6ad865cd1f7cfb846a5',
        'gateway': 'http://39.108.55.15/payapi.php/Home/Transfer/pay',
        'query_gateway': 'http://39.108.55.15/payapi.php/Home/Transfer/pay',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# $data['key']=md5($data["agentphone"].$data["amount"].$data["out_order_number"].$data["type"].$data["transfer"].$key);//签名验证
def generate_sign(d, key):
    s = d['agentphone'] + d['amount'] + d['out_order_number'] + d['type'] + d['transfer'] + key
    _LOGGER.info("shenglipay sign str: %s", s)
    return _gen_sign(s)


# md5('商户号+金额(元)+上送订单号+api+dmfalipaynet'.$key);
def generate_notify_sign(d, key):
    # s = d['cmchntid'] + '%.2f' % (int(d['amount']) / 100) + d['out_order_number'] + 'api' + 'dmfalipaynet' + key
    s = d['cmchntid'] + str(d['amount']) + d['out_order_number'] + 'api' + 'AlipayNet' + key
    _LOGGER.info("shenglipay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['key']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("shenglipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    # if service == 'alipay1':
    #     return 'AlipayNet'
    # else:
    #     return 'dmfalipaynet'
    return 'AlipayNet'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('agentphone', app_id),
        ('amount', str(int(pay_amount * 100))),
        ('out_order_number', str(pay.id)),
        ('title', 'charge'),
        ('description', 'charge'),
        ('callback', '{}/pay/api/{}/shenglipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('order_userid', str(pay.user_id)),
        ('type', 'api'),
        ('transfer', _get_pay_type(service)),
        ('is_encrypt', 1),
    ))
    parameter_dict['key'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("shenglipay create: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("shenglipay create rdp data: %s", response.text)
    return {'charge_info': json.loads(response.text)['data']['wap_url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("shenglipay notify data: %s", data)
    data['cmchntid'] = app_id
    verify_notify_sign(data, api_key)
    pay_id = data['out_order_number']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('shenglipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['tradeStatus'])
    trade_no = data['order_num']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态：S = 支付，R = 失败
    if trade_status == 'S':
        _LOGGER.info('shenglipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('agentphone', app_id),
        ('orderNo', str(pay_order.id)),
        ('type', 'api'),
        ('transfer', 'QUERY_ORDER'),
        ('is_encrypt', 1),
    ))
    _LOGGER.info('shenglipay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('shenglipay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['pay_status'])
        total_fee = float(data['money'])
        trade_no = data['orderNum']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '1':
            _LOGGER.info('shenglipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
